using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using VOL.Core.Filters;
using VOL.demo.IServices.Outbound;
using VOL.Entity.DomainModels;
using VOL.Core.Enums;

namespace VOL.WebApi.Controllers.demo
{
    /// <summary>
    /// 出库单控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OutboundController : ControllerBase
    {
        private readonly IOutboundIService _outboundService;

        public OutboundController(IOutboundIService outboundService)
        {
            _outboundService = outboundService;
        }

        /// <summary>
        /// 获取出入库类型下拉列表
        /// </summary>
        /// <returns>出入库类型列表</returns>
        [HttpGet("GetInOutTypes")]
        public async Task<IActionResult> GetInOutTypes()
        {
            try
            {
                Console.WriteLine("=== 获取出入库类型下拉列表开始 ===");

                // 调用服务层方法
                var result = await _outboundService.GetInOutTypeListAsync();

                Console.WriteLine($"查询结果: 共{result?.Count ?? 0}条记录");
                Console.WriteLine("✅ 获取出入库类型下拉列表成功");

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取出入库类型下拉列表异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取仓库下拉列表
        /// </summary>
        /// <returns>仓库列表</returns>
        [HttpGet("GetWarehouses")]
        public async Task<IActionResult> GetWarehouses()
        {
            try
            {
                Console.WriteLine("=== 获取仓库下拉列表开始 ===");

                // 调用服务层方法
                var result = await _outboundService.GetWarehouseListAsync();

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <returns>用户列表</returns>
        [HttpGet("GetUsers")]
        public async Task<IActionResult> GetUsers()
        {
            try
            {
                Console.WriteLine("=== 获取用户下拉列表开始 ===");

                // 调用服务层方法
                var result = await _outboundService.GetUserListAsync();

                Console.WriteLine($"查询结果: 共{result?.Count ?? 0}条记录");
                Console.WriteLine("✅ 获取用户下拉列表成功");

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取用户下拉列表异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据出入库类型ID分页查询销售订单
        /// </summary>
        /// <param name="inOutTypeId">出入库类型ID</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="orderCode">订单编号（可选）</param>
        /// <param name="customerName">客户名称（可选）</param>
        /// <returns>分页查询结果</returns>
        [HttpGet("GetSalesOrders/{inOutTypeId}")]
        public async Task<IActionResult> GetSalesOrders(
            long inOutTypeId,
            int pageIndex = 1,
            int pageSize = 20,
            string orderCode = null,
            string customerName = null)
        {
            try
            {
                Console.WriteLine($"=== 获取销售订单分页列表开始，出入库类型ID: {inOutTypeId} ===");
                Console.WriteLine($"参数: pageIndex={pageIndex}, pageSize={pageSize}, orderCode={orderCode}, customerName={customerName}");

                // 参数验证
                if (pageIndex <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "页码必须大于0" });
                }

                if (pageSize <= 0 || pageSize > 100)
                {
                    return BadRequest(new { Code = 400, Message = "每页记录数必须在1-100之间" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetSalesOrderPageListAsync(inOutTypeId, pageIndex, pageSize, orderCode, customerName);

                Console.WriteLine($"查询结果: 总记录数={result.TotalCount}, 当前页记录数={result.Data?.Count ?? 0}");

                // 构造分页响应
                var response = new
                {
                    data = result.Data,
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                };

                Console.WriteLine("✅ 获取销售订单分页列表成功");
                return Ok(new { Code = 200, Data = response, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取销售订单分页列表异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据出入库类型ID分页查询进货退货
        /// </summary>
        /// <param name="inOutTypeId">出入库类型ID</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="returnOrderCode">退货单号（可选）</param>
        /// <param name="supplierName">供应商名称（可选）</param>
        /// <returns>分页查询结果</returns>
        [HttpGet("GetReturnOrders/{inOutTypeId}")]
        public async Task<IActionResult> GetReturnOrders(
            long inOutTypeId,
            int pageIndex = 1,
            int pageSize = 20,
            string returnOrderCode = null,
            string supplierName = null)
        {
            try
            {
                Console.WriteLine($"=== 获取进货退货分页列表开始，出入库类型ID: {inOutTypeId} ===");
                Console.WriteLine($"参数: pageIndex={pageIndex}, pageSize={pageSize}, returnOrderCode={returnOrderCode}, supplierName={supplierName}");

                // 参数验证
                if (pageIndex <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "页码必须大于0" });
                }

                if (pageSize <= 0 || pageSize > 100)
                {
                    return BadRequest(new { Code = 400, Message = "每页记录数必须在1-100之间" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetReturnOrderPageListAsync(inOutTypeId, pageIndex, pageSize, returnOrderCode, supplierName);

                Console.WriteLine($"查询结果: 总记录数={result.TotalCount}, 当前页记录数={result.Data?.Count ?? 0}");

                // 构造分页响应
                var response = new
                {
                    data = result.Data,
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                };

                Console.WriteLine("✅ 获取进货退货分页列表成功");
                return Ok(new { Code = 200, Data = response, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取进货退货分页列表异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据销售订单ID查询销售订单明细
        /// </summary>
        /// <param name="shopOrderId">销售订单ID</param>
        /// <returns>销售订单明细列表</returns>
        [HttpGet("GetSalesOrderDetails/{shopOrderId}")]
        public async Task<IActionResult> GetSalesOrderDetails(long shopOrderId)
        {
            try
            {
                Console.WriteLine($"=== 获取销售订单明细开始，销售订单ID: {shopOrderId} ===");

                // 参数验证
                if (shopOrderId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "销售订单ID必须大于0" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetSalesOrderDetailsByIdAsync(shopOrderId);

                Console.WriteLine($"查询结果: 共{result?.Count ?? 0}条明细记录");
                Console.WriteLine("✅ 获取销售订单明细成功");

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取销售订单明细异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据退货订单ID查询退货订单明细
        /// </summary>
        /// <param name="returnOrderId">退货订单ID</param>
        /// <returns>退货订单明细列表</returns>
        [HttpGet("GetReturnOrderDetails/{returnOrderId}")]
        public async Task<IActionResult> GetReturnOrderDetails(long returnOrderId)
        {
            try
            {
                Console.WriteLine($"=== 获取退货订单明细开始，退货订单ID: {returnOrderId} ===");

                // 参数验证
                if (returnOrderId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "退货订单ID必须大于0" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetReturnOrderDetailsByIdAsync(returnOrderId);

                Console.WriteLine($"查询结果: 共{result?.Count ?? 0}条明细记录");
                Console.WriteLine("✅ 获取退货订单明细成功");

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取退货订单明细异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 退货出库（事务性操作）
        /// </summary>
        /// <param name="request">退货出库请求</param>
        /// <returns>出库单ID</returns>
        [HttpPost("CreateReturnOutbound")]
        public async Task<IActionResult> CreateReturnOutbound([FromBody] ReturnOutboundRequestDto request)
        {
            try
            {
                Console.WriteLine($"=== 退货出库开始 ===");
                Console.WriteLine($"出库编号: {request?.OutboundCode}, 退货订单ID: {request?.RelationalID}");

                // 参数验证
                if (request == null)
                {
                    return BadRequest(new { Code = 400, Message = "请求参数不能为空" });
                }

                if (string.IsNullOrWhiteSpace(request.OutboundCode))
                {
                    return BadRequest(new { Code = 400, Message = "出库编号不能为空" });
                }

                if (request.OutInTypeId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "出库类型ID必须大于0" });
                }

                if (request.WarehouseId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "仓库ID必须大于0" });
                }

                if (request.RelationalID <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "关联单号（退货订单ID）必须大于0" });
                }

                if (request.UserId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "用户ID必须大于0" });
                }

                if (request.Details == null || request.Details.Count == 0)
                {
                    return BadRequest(new { Code = 400, Message = "出库明细不能为空" });
                }

                // 验证明细数据
                for (int i = 0; i < request.Details.Count; i++)
                {
                    var detail = request.Details[i];
                    if (detail.DetailId <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的关联明细ID（退货明细ID）必须大于0" });
                    }
                    if (detail.StorageId <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的库位ID必须大于0" });
                    }
                    if (detail.OneOutboundNum <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的出库数量必须大于0" });
                    }
                }

                // 调用服务层方法
                var outboundId = await _outboundService.CreateReturnOutboundAsync(request);

                Console.WriteLine($"✅ 退货出库成功，出库单ID: {outboundId}");

                return Ok(new { 
                    Code = 200, 
                    Data = new { OutboundId = outboundId }, 
                    Message = "退货出库成功" 
                });
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"❌ 退货出库参数错误: {ex.Message}");
                return BadRequest(new { Code = 400, Message = ex.Message });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 退货出库异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"退货出库失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 销售订单出库（事务性操作）
        /// </summary>
        /// <param name="request">销售订单出库请求</param>
        /// <returns>出库单ID</returns>
        [HttpPost("CreateSalesOutbound")]
        public async Task<IActionResult> CreateSalesOutbound([FromBody] SalesOutboundRequestDto request)
        {
            try
            {
                Console.WriteLine($"=== 销售订单出库开始 ===");
                Console.WriteLine($"出库编号: {request?.OutboundCode}, 销售订单ID: {request?.RelationalID}");

                // 参数验证
                if (request == null)
                {
                    return BadRequest(new { Code = 400, Message = "请求参数不能为空" });
                }

                if (string.IsNullOrWhiteSpace(request.OutboundCode))
                {
                    return BadRequest(new { Code = 400, Message = "出库编号不能为空" });
                }

                if (request.OutInTypeId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "出库类型ID必须大于0" });
                }

                if (request.WarehouseId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "仓库ID必须大于0" });
                }

                if (request.RelationalID <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "关联单号（销售订单ID）必须大于0" });
                }

                if (request.UserId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "用户ID必须大于0" });
                }

                if (request.Details == null || request.Details.Count == 0)
                {
                    return BadRequest(new { Code = 400, Message = "出库明细不能为空" });
                }

                // 验证明细数据
                for (int i = 0; i < request.Details.Count; i++)
                {
                    var detail = request.Details[i];
                    if (detail.DetailId <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的关联明细ID（销售订单明细ID）必须大于0" });
                    }
                    if (detail.StorageId <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的库位ID必须大于0" });
                    }
                    if (detail.OneOutboundNum <= 0)
                    {
                        return BadRequest(new { Code = 400, Message = $"第{i + 1}条明细的出库数量必须大于0" });
                    }
                }

                // 调用服务层方法
                var outboundId = await _outboundService.CreateSalesOutboundAsync(request);

                Console.WriteLine($"✅ 销售订单出库成功，出库单ID: {outboundId}");

                return Ok(new { 
                    Code = 200, 
                    Data = new { OutboundId = outboundId }, 
                    Message = "销售订单出库成功" 
                });
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"❌ 销售订单出库参数错误: {ex.Message}");
                return BadRequest(new { Code = 400, Message = ex.Message });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 销售订单出库异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"销售订单出库失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 分页查询出库单（多表联查）
        /// </summary>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="outboundCode">出库编号（可选）</param>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>分页查询结果</returns>
        [HttpGet]

        public async Task<IActionResult> GetOutbound(
            int pageIndex = 1,
            int pageSize = 20,
            string outboundCode = null,
            long? userId = null)
        {
            try
            {
                Console.WriteLine("=== 出库单分页查询开始 ===");
                Console.WriteLine($"参数: pageIndex={pageIndex}, pageSize={pageSize}, outboundCode={outboundCode}, userId={userId}");

                // 参数验证
                if (pageIndex <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "页码必须大于0" });
                }

                if (pageSize <= 0 || pageSize > 100)
                {
                    return BadRequest(new { Code = 400, Message = "每页记录数必须在1-100之间" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetPageListWithRelationsAsync(pageIndex, pageSize, outboundCode, userId);

                Console.WriteLine($"查询结果: 总记录数={result.TotalCount}, 当前页记录数={result.Data?.Count ?? 0}");

                // 构造分页响应
                var response = new
                {
                    data = result.Data,
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                };

                Console.WriteLine("✅ 出库单分页查询成功");
                return Ok(new { Code = 200, Data = response, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 出库单分页查询异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }
        /// <summary>
        /// 根据出库ID查询出库明细列表（多表联查）
        /// </summary>
        /// <param name="outboundId">出库单ID</param>
        /// <returns>出库明细列表</returns>
        [HttpGet("GetOutboundDetails/{outboundId}")]
        public async Task<IActionResult> GetOutboundDetails(long outboundId)
        {
            try
            {
                Console.WriteLine($"=== 获取出库明细开始，出库单ID: {outboundId} ===");

                // 参数验证
                if (outboundId <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "出库单ID必须大于0" });
                }

                // 调用服务层方法
                var result = await _outboundService.GetOutboundDetailsByIdAsync(outboundId);

                Console.WriteLine($"查询结果: 共{result?.Count ?? 0}条出库明细记录");
                Console.WriteLine("✅ 获取出库明细成功");

                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取出库明细异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

    }
}
